package com.tool.cn.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Http 工具类
 * 
 * @author wangzh
 * 2018年1月2日 下午3:34:38
 */
public final class HttpUtil {



	private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
	
	private static final String defaultEncode="utf-8";
	
	private static final int connectionTime=10*1000;
	private static final int readTimeout=10*1000;
	
	
	/**
	 * get请求编码utf-8
	 * @param url 请求地址
	 * @return
	 */
	public static String doHttpGet(String url) {
		return doHttpGet(url, defaultEncode);
	}
	
	/**
	 * get 请求
	 * @param url 请求地址
	 * @param Encode 
	 * @return
	 */
	public static String doHttpGet(String url,String encode){
		 BufferedReader reader = null; 
		try {
	            URL realUrl = new URL(url);
	            
	            URLConnection conn = realUrl.openConnection();
	            conn.setConnectTimeout(connectionTime);
	            conn.setReadTimeout(readTimeout);
	            
	            reader = new BufferedReader(new InputStreamReader(realUrl.openStream(),encode));
	            StringBuilder buf=new StringBuilder();
	            String line;
	            while((line = reader.readLine()) != null){
	                buf.append(line);
	            }
	            
	            return buf.toString();
	        } catch (Exception e) {
	        	log.error(url+" "+e.toString(),e);
	        }finally {
	        	if(reader!=null) {
	        		try {
						reader.close();
					} catch (IOException e) {
						log.error(url+" "+e.toString(),e);
					}
	        	}
	        }
		 return "";
	}
	

	/**
	 * http post请求，参数格式json，编码utf-8
	 * @param url 请求地址
	 * @param info json信息
	 * @return
	 */
	public static String doHttpPostJson(String url,String info)  {
		return doHttpPost(url,info,  "application/json",defaultEncode);
	}
	
	/**
	 * http post请求，参数格式json
	 * @param url 请求地址
	 * @param info json信息
	 * @param encode 编码
	 * @return
	 */
	public static String doHttpPostJson(String url,String info,String encode)  {
		return doHttpPost(url,info,  "application/json",encode);
	}
	
	/**
	 * http post请求，参数格式xml，编码utf-8
	 * @param url 请求地址
	 * @param info xml信息
	 * @return
	 */
	public static String doHttpPostXml( String url,String info)  {
		return doHttpPost(url, info, "text/xml",defaultEncode);
	}
	
	/**
	 * http post请求，参数格式xml
	 * @param url 请求地址
	 * @param info xml信息
	 * @param encode 编码
	 * @return
	 */
	public static String doHttpPostXml( String url,String info,String encode)  {
		return doHttpPost(url, info, "text/xml",encode);
	}
	

	/**
	 * post 请求
	 * @param info  请求信息
	 * @param URL 请求地址
	 * @param application 请求类型：json为：application/json xml为：text/xml
	 * @param encode 编码
	 * @return
	 */
	public static String doHttpPost(String URL,String info, String application,String encode) {
		byte[] jsonData = info.getBytes();
		BufferedReader reader=null;

		try {
			URL url = new URL(URL);
			URLConnection urlCon = url.openConnection();
			urlCon.setDoOutput(true);
			urlCon.setDoInput(true);
			urlCon.setUseCaches(false);
			
			urlCon.setConnectTimeout(connectionTime);
			urlCon.setReadTimeout(readTimeout);
            
			urlCon.setRequestProperty("Content-Type",application);
			urlCon.setRequestProperty("Content-length", String.valueOf(jsonData.length));
			
			DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
			printout.write(jsonData);
			printout.flush();
			printout.close();
			
			  reader = new BufferedReader(new InputStreamReader(urlCon.getInputStream(),encode));
	            StringBuffer buf=new StringBuffer();
	            String line;
	            while((line = reader.readLine()) != null){
	                buf.append(line);
	            }
			
	            return buf.toString();
		}catch(Exception e){
			log.error(URL+" "+e.toString(),e);
		} finally {
			if(reader!=null) {
				try {
					reader.close();
				} catch (IOException e) {
					log.error(URL+" "+e.toString(),e);
				}
			}
		}
		return "";
	}
	
	/**
	 * http put请求，参数格式json，编码utf-8
	 * @param url 请求地址
	 * @param info json信息
	 * @return
	 */
	public static String doHttpPutJson(String url,String info)  {
		return doHttpPut(url,info,  "application/json",defaultEncode);
	}
	
	/**
	 * http put请求，参数格式json
	 * @param url 请求地址
	 * @param info json信息
	 * @param encode 编码
	 * @return
	 */
	public static String doHttpPutJson(String url,String info,String encode)  {
		return doHttpPut(url,info,  "application/json",encode);
	}
	
	/**
	 * http put请求，参数格式xml，编码utf-8
	 * @param url 请求地址
	 * @param info xml信息
	 * @return
	 */
	public static String doHttpPutXml( String url,String info)  {
		return doHttpPut(url, info, "text/xml",defaultEncode);
	}
	
	/**
	 * http put请求，参数格式xml
	 * @param url 请求地址
	 * @param info xml信息
	 * @param encode 编码
	 * @return
	 */
	public static String doHttpPutXml( String url,String info,String encode)  {
		return doHttpPut(url, info, "text/xml",encode);
	}
	
	
	/**
	 * http put请求
	 * @param URL  请求地址
	 * @param info 请求信息
	 * @param application 信息类型
	 * @param encode 编码
	 * @return
	 */
    public static String doHttpPut(String url,String info, String application,String encode) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTime).setConnectionRequestTimeout(connectionTime).setSocketTimeout(connectionTime).build();
        httpPut.setConfig(requestConfig);
        httpPut.setHeader("Content-type", application);
        httpPut.setHeader("DataEncoding", encode);
//        httpPut.setHeader("token", token);
        
        CloseableHttpResponse httpResponse = null;
        try {
            httpPut.setEntity(new StringEntity(info));
            httpResponse = httpClient.execute(httpPut);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (Exception e) {
        	log.error("Connecttion Url:"+url+" Error"+e.toString(),e);
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (Exception e) {
                    log.error("Close Url:"+url+" Error"+e.toString(),e);
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (Exception e) {
                	log.error("Close Url:"+url+" Error"+e.toString(),e);
                }
            }
        }
        return "";
    }


    	/**
    	 * delete请求
    	 * @param url 请求地址 请求地址
    	 * @return
    	 */
    public static String doDelete(String url) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpDelete = new HttpDelete(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTime).setConnectionRequestTimeout(connectionTime).setSocketTimeout(connectionTime).build();
        
        httpDelete.setConfig(requestConfig);
        
//        httpDelete.setHeader("Content-type", application);
//        httpDelete.setHeader("DataEncoding", encode);

        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpDelete);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (Exception e) {
        	log.error("Connecttion Url:"+url+" Error"+e.toString(),e);
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (Exception e) {
                	log.error("Close Url:"+url+" Error"+e.toString(),e);
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (Exception e) {
                	log.error("Close Url:"+url+" Error"+e.toString(),e);
                }
            }
        }
        return "";
    }
}
